<?php
namespace Home\Controller;
use Think\Controller;
class CommonController extends Controller {
	public function _initialize(){
		if(!C('WEB_ON')) die('网站维护中...');
		$this->top_cate();//顶部分类
		$this->ask_num();//顶部提问数
		$this->right_con();//右侧内容
	}
	//顶部分类
    public function top_cate()
    {
    	$top_cate=M('category')->where(array('pid'=>0))->select();    	
		$this->assign('topCate',$top_cate);
    }
	//累计提问
	public function ask_num(){
		$ask_num=M('ask')->count();
		$this->assign('askNum',$ask_num);
	}
	//获取父栏目
	public function parent_cate($arr,$pid){
		$array=array();
		foreach ($arr as $v) {
			if($v['cid']==$pid){
				$array[]=$v;
				$array=array_merge($array,$this->parent_cate($arr,$v['pid']));
			}
			
		}
		return $array;
	}
	//头像
	public function face($user){
		if(empty($user['face'])){
			return __ROOT__.'/Public/Home/Images/noface.gif';
		}else{
			return $user['face'];
		}
	}
	//经验转换等级
	public function exp_to_level($exp){
		for($i=0;$i<21;$i++){
			if($exp<=C('LV'.$i)){
				return $i;
			}
			if($exp>C('LV20')){
				return 20;
			}
		}
	}
	//采纳率
	public function adoptBfb($answer,$adopt){
		return round(($adopt/$answer)*100,2);
		
	}
	
	//右侧内容区
	public function right_con(){
		$user=M('user');
		//右侧头像内容
		$uid=I('session.uid',null,'intval');
		if($uid){
			$field='username,exp,gold,face,answer,ask,adopt,uid';
			$loginUser=$user->field($field)->where(array('uid'=>$uid))->find();
			$loginUser['face']=$this->face($loginUser);
			$loginUser['level']=$this->exp_to_level($loginUser['exp']);
			$loginUser['adoptBfb']=$this->adoptBfb($loginUser['answer'], $loginUser['adopt']);
			$this->assign('loginUser',$loginUser);
		}		
		//本日回答问题最多的人
		$time=strtotime(date('Y-m-d'));
		$mostToday=D('answer')->field('username,uanswer,face,exp,uadopt,time,uid')->group('username')->where(array('time'=>array('GT',$time)))->order('count(username) desc')->find();//通过分组group 统计排序
		if(!empty($mostToday)){
			$mostToday['level']=$this->exp_to_level($mostToday['exp']);
			$mostToday['face']=$this->face($mostToday);
			$mostToday['adoptBfb']=$this->adoptBfb($mostToday['uanswer'], $mostToday['uadopt']);
		}
		$this->assign('mostToday',$mostToday);
		//p($mostToday);
		//历史回答问题最多的人
		$mostAnswer=$user->field('username,face,answer,adopt,exp,uid')->order('answer desc')->find();
		$mostAnswer['level']=$this->exp_to_level($mostAnswer['exp']);
		$mostAnswer['face']=$this->face($mostAnswer);
		$mostAnswer['adoptBfb']=$this->adoptBfb($mostAnswer['answer'], $mostAnswer['adopt']);
		$this->assign('mostAnswer',$mostAnswer);
		
		//光荣榜
		$honor=$user->field('username,adopt,uid')->where(array('adopt'=>array('GT',0)))->order('adopt desc')->limit(5)->select();
		$this->assign('honor',$honor);		
		
	}
	
}	
	
